#pragma once
#include "TcpServer.hpp"
#include "HttpProtocal.hpp"

using namespace HttpProtocalModule;

class HttpServer
{
public:
    HttpServer(uint16_t port):
        _tcvr(std::make_unique<TcpServer>(port)),
        _port(port)
    {}

    void InitServer()
    {
        _tcvr->InitServer(HandlerRequest);
        _tcvr->Loop();
    }
    static void HandlerRequest(std::string request,std::shared_ptr<TcpSocket> tcsr)
    {
        // 第二个参数负责返回的作用
        // 拿到了一个request

        Request req;
        if(req.Deserialize(request) == false){
            // 
            LOG(LogLevel::ERROR) << "反序列化失败";
            return;
        }

        std::cout << "method:" << req.Method() << " uri:" << req.Uri() << " version:" << req.Version() << std::endl;
         
        Response rsps;
        
        rsps.Build(req);
        std::string rsps_str;
        rsps.Serialize(&rsps_str);
        // std::cout << "返回的Response:" << std::endl;
        // std::cout << rsps_str << std::endl; // 打印我们序列化的数据
        tcsr->SendTo(rsps_str);
        tcsr->Close(tcsr->SockForCommunicate());
    }

    void Stop()
    {
        _tcvr->Stop();
    }
private:
    std::unique_ptr<TcpServer> _tcvr;
    uint16_t _port;
};